package activity.Left;

import android.animation.ObjectAnimator;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hichip.campro.R;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import activity.Left.adapter.VpPhotoVideoAdapter;
import base.HiActivity;
import bean.LeftLocalFileBean;
import bean.MyCamera;
import butterknife.BindView;
import common.HiDataValue;
import custom.dialog.NiftyDialogBuilder;
import custom.stickygridview.GridItem;
import utils.HiToast;
import utils.HiTools;
import utils.SharePreUtils;
/**
 * 照片和录像 tab界面
 */
public class LeftLocalVideoPhotoActivity extends HiActivity implements View.OnClickListener {
    @BindView(R.id.iv_return) ImageView iv_return;
    @BindView(R.id.title_middle) TextView title_middle;
    @BindView(R.id.tv_uid) TextView tv_uid;
    @BindView(R.id.tv_right) TextView tv_right;
    @BindView(R.id.tablayout) TabLayout tablayout;
    @BindView(R.id.viewPager) ViewPager viewPager;
    @BindView(R.id.ll_anim) LinearLayout ll_anim;
    private VpPhotoVideoAdapter mAdaper;
    private LeftLocalFileBean bean;
    private boolean isDeleteModel = false;//当前是否是删除模式
    private LeftGetDataModel mModel;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_left_local_video_photo;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        mModel = LeftGetDataModel.getInstance();
        initView();
        setListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshDataAndView();
    }

    private void refreshDataAndView() {
        tablayout.getTabAt(0).setText(getString(R.string.video_colon) + mModel.getVoideNum(bean.getFile().getAbsolutePath()));
        tablayout.getTabAt(1).setText(getString(R.string.photo_colon) + mModel.getPhotoNum(bean.getFile().getAbsolutePath()));
    }


    private void setListeners() {
        iv_return.setOnClickListener(this);
        tv_right.setOnClickListener(this);
        ll_anim.setOnClickListener(this);
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                Fragment fragment = mAdaper.getItem(tablayout.getSelectedTabPosition());
                if (fragment instanceof LeftLocalPhotoFragment) {
                    LeftLocalPhotoFragment leftLocalPhotoFragment = (LeftLocalPhotoFragment) fragment;
                    leftLocalPhotoFragment.mAdapter.setDelMode(0);
                    leftLocalPhotoFragment.mDeleteList.clear();
                }
                if(fragment instanceof LeftLocalVideoFragment){
                    LeftLocalVideoFragment leftLocalVideoFragment= (LeftLocalVideoFragment) fragment;
                    leftLocalVideoFragment.mAdapter.setDelMode(0);
                    leftLocalVideoFragment.mDeleteList.clear();
                }

                if (isDeleteModel) {
                    loadAnimation(HiTools.dip2px(LeftLocalVideoPhotoActivity.this, 50));
                    tv_right.setText(getString(R.string.edit));
                    fragment = mAdaper.getItem(tablayout.getSelectedTabPosition());
                    if (fragment instanceof LeftLocalPhotoFragment) {
                        LeftLocalPhotoFragment leftLocalPhotoFragment = (LeftLocalPhotoFragment) fragment;
                        leftLocalPhotoFragment.mAdapter.setDelMode(0);
                        leftLocalPhotoFragment.mDeleteList.clear();
                    }
                    if(fragment instanceof LeftLocalVideoFragment){
                        LeftLocalVideoFragment leftLocalVideoFragment= (LeftLocalVideoFragment) fragment;
                        leftLocalVideoFragment.mAdapter.setDelMode(0);
                        leftLocalVideoFragment.mDeleteList.clear();
                    }
                    isDeleteModel=!isDeleteModel;
                }
            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    private void getIntentData() {
        bean = (LeftLocalFileBean) getIntent().getSerializableExtra("bean");
    }

    private void initView() {
        if (bean != null) {
            for (MyCamera camera : HiDataValue.CameraList) {
                if (camera.getUid().equals(bean.getUid())) {
                    Log.i("tedu","--NickName--:"+camera.getNikeName());
                    title_middle.setText(camera.getNikeName());
                    break;
                }
            }
            tv_uid.setText(bean.getUid());
        }
        tablayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tablayout,30,30);
            }
        });
        tablayout.addTab(tablayout.newTab().setText(getString(R.string.video_colon)+ bean.getVoideNum()));
        tablayout.addTab(tablayout.newTab().setText(getString(R.string.photo_colon) + bean.getPhotoNum()));

        List<Fragment> fragments = new ArrayList<>();
        Bundle bundle = new Bundle();
        bundle.putSerializable("bean", bean);

        LeftLocalVideoFragment leftLocalVideoFragment = new LeftLocalVideoFragment();
        leftLocalVideoFragment.setArguments(bundle);
        fragments.add(leftLocalVideoFragment);

        LeftLocalPhotoFragment leftLocalPhotoFragment = new LeftLocalPhotoFragment();
        leftLocalPhotoFragment.setArguments(bundle);
        fragments.add(leftLocalPhotoFragment);



        List<String> titles = new ArrayList<>();
        titles.add(getString(R.string.video_colon) + bean.getVoideNum());
        titles.add(getString(R.string.photo_colon) + bean.getPhotoNum());

        mAdaper = new VpPhotoVideoAdapter(getSupportFragmentManager(), fragments, titles);
        viewPager.setAdapter(mAdaper);
        tablayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_return:
                LeftLocalVideoPhotoActivity.this.finish();
                break;
            case R.id.tv_right:// 右边编辑和完成
                handEditDone();
                break;
            case R.id.ll_anim:  //删除
                handDelete();
                break;

        }

    }

    private void handDelete() {
        Fragment fragment = mAdaper.getItem(tablayout.getSelectedTabPosition());
        if (fragment instanceof LeftLocalPhotoFragment) {
            LeftLocalPhotoFragment leftLocalPhotoFragment = (LeftLocalPhotoFragment) fragment;
            if(leftLocalPhotoFragment.mDeleteList.size()<1){
                HiToast.showToast(this,getString(R.string.select_delete_photo));
                return;
            }
        }
        if(fragment instanceof LeftLocalVideoFragment){
            LeftLocalVideoFragment leftLocalVideoFragment= (LeftLocalVideoFragment) fragment;
            if(leftLocalVideoFragment.mDeleteList.size()<1){
                HiToast.showToast(this,getString(R.string.select_delect_video));
                return;
            }
        }

        final NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(LeftLocalVideoPhotoActivity.this);
        String string="";
        if (fragment instanceof LeftLocalPhotoFragment) {
            string=getString(R.string.tips_msg_delete_snapshot);
        }else {
            string=getString(R.string.confirm_delete_video);
        }
        dialog.withMessage(string).withButton1Text(getString(R.string.btn_no)).withButton2Text(getString(R.string.btn_ok)).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if (fragment instanceof LeftLocalPhotoFragment) {
                    LeftLocalPhotoFragment leftLocalPhotoFragment = (LeftLocalPhotoFragment) fragment;
                    handPhotoFragmentData(leftLocalPhotoFragment);
                }
                if(fragment instanceof LeftLocalVideoFragment){
                    LeftLocalVideoFragment leftLocalVideoFragment= (LeftLocalVideoFragment) fragment;
                    handVideoFragmentData(leftLocalVideoFragment);
                }
            }
        }).show();
    }

    private void handEditDone() {
        tv_right.setText(isDeleteModel ? getString(R.string.edit):getString(R.string.finish));
        Fragment fragment = mAdaper.getItem(tablayout.getSelectedTabPosition());
        if (fragment instanceof LeftLocalPhotoFragment) {
            LeftLocalPhotoFragment leftLocalPhotoFragment = (LeftLocalPhotoFragment) fragment;
            leftLocalPhotoFragment.mAdapter.setDelMode(isDeleteModel ? 0 : 1);
            leftLocalPhotoFragment.mDeleteList.clear();
            if (isDeleteModel) {
                loadAnimation(HiTools.dip2px(LeftLocalVideoPhotoActivity.this, 50));
            } else {
                loadAnimation(HiTools.dip2px(LeftLocalVideoPhotoActivity.this, -50));
            }
        }
        if(fragment instanceof LeftLocalVideoFragment){
            LeftLocalVideoFragment leftLocalVideoFragment= (LeftLocalVideoFragment) fragment;
            leftLocalVideoFragment.mAdapter.setDelMode(isDeleteModel ? 0 : 1);
            leftLocalVideoFragment.mDeleteList.clear();
            if (isDeleteModel) {
                loadAnimation(HiTools.dip2px(LeftLocalVideoPhotoActivity.this, 50));
            } else {
                loadAnimation(HiTools.dip2px(LeftLocalVideoPhotoActivity.this, -50));
            }
        }
        isDeleteModel = !isDeleteModel;
    }

    private void handPhotoFragmentData(LeftLocalPhotoFragment leftLocalPhotoFragment) {
        for (GridItem gridItem : leftLocalPhotoFragment.mDeleteList) {
            File file = new File(gridItem.getPath());
            file.delete();
        }
        leftLocalPhotoFragment.mGirdList.removeAll(leftLocalPhotoFragment.mDeleteList);
        for (int i = 0; i < leftLocalPhotoFragment.mAdapter.checks.length - leftLocalPhotoFragment.mDeleteList.size(); i++) {
            leftLocalPhotoFragment.mAdapter.checks[i] = false;
        }
        leftLocalPhotoFragment.mAdapter.notifyDataSetChanged();
        leftLocalPhotoFragment.mDeleteList.clear();
        refreshDataAndView();
    }

    private void handVideoFragmentData(LeftLocalVideoFragment leftLocalVideoFragment) {
        for (GridItem gridItem : leftLocalVideoFragment.mDeleteList) {
            File file = new File(gridItem.getPath());
            file.delete();
            String[]  strs=gridItem.getPath().split("/");
            String str=strs[strs.length-1];
            File file1=new File(HiDataValue.getPathCameraLocalRecordSnapShot(bean.getUid(),this)+"/SnapShot/"+str);
            if(file1!=null&&file1.exists()&&file1.isFile()){
                file1.delete();
            }
            String[] s=str.split("\\.");
            if(s.length>0){
                String mystr=s[0];
                SharePreUtils.removeKey(HiDataValue.CACHE,LeftLocalVideoPhotoActivity.this,mystr);
            }
        }
        leftLocalVideoFragment.mGirdList.removeAll(leftLocalVideoFragment.mDeleteList);
        for (int i = 0; i < leftLocalVideoFragment.mAdapter.checks.length - leftLocalVideoFragment.mDeleteList.size(); i++) {
            leftLocalVideoFragment.mAdapter.checks[i] = false;
        }
        leftLocalVideoFragment.mAdapter.notifyDataSetChanged();
        leftLocalVideoFragment.mDeleteList.clear();
        refreshDataAndView();
    }

    /**
     * 加载动画效果
     */
    private void loadAnimation(float values) {
        float curTranslationY = ll_anim.getTranslationY();
        ObjectAnimator animator = ObjectAnimator.ofFloat(ll_anim, "translationY", curTranslationY, values);
        animator.setDuration(250);
        animator.start();
    }

    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }
}
